var main = {
	init : function() {
		main.nav = $('#nav');
		main.tabs = $('#tabs');
		main.tabMenu = $('#tabMenu');
		main.clickMenu = $('#clickMenu');
		main.stuViwExamDialog=$('#stuViwExamDialog');
		main.stuViwExamPanel=$('#stuViwExamPanel');
		// 初始化tab，并创建右键菜单
		main.tabs.tabs({
			border : false,
			fit : true,
			onContextMenu : function(e, title, index) {
				e.preventDefault();
				if (index > 0) {
					main.tabMenu.menu('show', {
						left : e.pageX,
						top : e.pageY
					}).data("tabTitle", title);
				}
			}
		});
		
		// 请求tree数据
		main.nav.tree({
			url : window.ctx + '/test/TestServlet?command=listMenu',
			lines : true,
			onLoadSuccess : function(node, data) {
				main.nav.tree('expandAll')
			},
			onClick : function(node) {
				if (node.url) {
					if (main.tabs.tabs('exists', node.text)) {
						main.tabs.tabs('select', node.text)
					} else {
						main.tabs.tabs('add', {
							title : node.text,
							iconCls : node.iconCls,
							closable : true,
							href : window.ctx + node.url
						});
					}
				}
			}
		});
		//Datagrid里的右键菜单
		main.clickMenu.menu({
			onClick : function(item) {
				var rowDataId = $(this).data("rowDataId");
				switch (item.name) {
				case 'delete':
					user.toolbar.remove(rowDataId);
					break;
				case 'update':
					user.toolbar.showUpdateDialog(rowDataId);
					break;
				case 'open':
					user.toolbar.open(rowDataId);
					break;
				case 'refresh':
					user.userGrid.datagrid('reload');
					break;
				case 'close':
					user.toolbar.close(rowDataId);
					break;
				}
				
			}
		});
		// 右键菜单click
		main.tabMenu.menu({
			onClick : function(item) {
				var allTabs = main.tabs.tabs('tabs');
				var allTabtitle = [];
				$.each(allTabs, function(i, v) {
					var opt = $(v).panel('options');
					if (opt.closable) {
						allTabtitle.push(opt.title);
					}
				});
				var curTabTitle = $(this).data("tabTitle");
				var curTabIndex = main.tabs.tabs("getTabIndex", main.tabs.tabs(
						"getTab", curTabTitle));
				switch (item.name) {
				case 'refresh':
					var panel = main.tabs.tabs("getTab", curTabTitle).panel(
							"refresh");
					break;
				case 'closeCurrent':
					main.tabs.tabs("close", curTabIndex);
					break;
				case 'closeOther':
					$.each(allTabtitle, function(i, v) {
						if (curTabTitle != allTabtitle[i]) {
							main.tabs.tabs('close', allTabtitle[i]);
						}
					});
					main.tabs.tabs('select', curTabTitle);
					break;
				case 'closeAll':
					$.each(allTabtitle, function(i, v) {
						main.tabs.tabs('close', allTabtitle[i]);
					});
					break;
				}
			}
		});
		
		main.stuViwExamDialog.datagrid({
		    url: window.ctx + '/StuServlet?command=listStu',
		    fitColumns: true,
		    striped: true,
		    rownumbers: true,
		    pagination: true,
		    pageSize: 10,
		    pageList: [10, 20, 30, 40, 50],
		    pageNumber: 1,
		    toolbar: '#stuViewExamToolbar',
		    columns:[[
				{field:'id', width:100, checkbox: true},
				{field:'exam_time_start', title:'考试时间（起）', width:100, align:'center'},
				{field:'exam_time_stop', title:'考试时间（止）', width:100, align:'center'},
				{field:'exam_classroom', title:'考试教室', width:100, align:'center'},
				{field:'pagename', title:'试卷名称', width:100, align:'center'},
				{field:'username', title:'操作者', width:100, align:'center'},
				{field:'operate_time', title:'操作时间', width:100, align:'center'}
		    ]],
		});
		
		//欢迎页
		$.post(window.ctx +'/AssistNewNoticeServlet?command=listUserPower', function(data) {
			var json = eval('('+data+')');
			if (json.id==3) {
				main.stuViwExamPanel.panel({
					href:window.ctx +'/view/assist/main-Snew-notice.jsp',
					fit:true,
				});
			} else {
				main.stuViwExamPanel.panel({
					href:window.ctx +'/assets/mainType/default.jsp',
					fit:true,
				});
			}
		});
		
	},
	toolbar:{
		startExam: function(id){
			$.post(window.ctx + '/exam/PaperServlet?command=getPaper', {examPlanId:id}, function(data) {
				if (data) {
					$('#examPaperName').text(data.name);
					$('#examCourse').text(data.courseName);
					$('#examType').text(data.paperType);
					$('#examTotal').text(data.totalPoint);
					$('#examTime').text(data.totalMinutes);
					$(function(){
					    var m=data.totalMinutes-1;
					    var s=59;
					    setInterval(function(){
					        if(s<10){
					            $('#time').html(m+':0'+s);
					        }else{
					            $('#time').html(m+':'+s);
					        }
					        s--;
					        if(s<0){
					            s=59;
					            m--;
					        }
					        if(m==0 && s==0){
						    	main.toolbar.submitPaper();
						    }
					    },1000)
					   
					});
					$('#examTime').append('<input type="hidden" name="questionNumber" value="'+(data.singleOptionNumber + data.multiOptionNumber + data.judgeNumber)+'">');
					$('#examTotal').append('<input type="hidden" name="passPoint" value="'+ data.passPoint +'">');
					for (var i=0;i < data.singleOptionNumber;i++){
						$('#single').append('<li><strong>'+ data.questionList[i].question +'</strong><br></li>');
						$('#single').append('<input type="radio" name="question'+ i +'" value="A">A:  '+data.questionList[i].answerA +'<br>');
						$('#single').append('<input type="radio" name="question'+ i +'" value="B">B:  '+data.questionList[i].answerB +'<br>');
						$('#single').append('<input type="radio" name="question'+ i +'" value="C">C:  '+data.questionList[i].answerC +'<br>');
						$('#single').append('<input type="radio" name="question'+ i +'" value="D">D:  '+data.questionList[i].answerD +'<br>');
						$('#single').append('<input type="hidden" name="questionId'+ i +'" value="'+data.questionList[i].id+'">');
						
					}
					for (var i=data.singleOptionNumber;i < data.singleOptionNumber+data.multiOptionNumber;i++){
						$('#multi').append('<li><strong>'+ data.questionList[i].question +'</strong><br></li>');
						$('#multi').append('<input type="checkbox" name="question'+ i +'" value="A">A:  '+data.questionList[i].answerA +'<br>');
						$('#multi').append('<input type="checkbox" name="question'+ i +'" value="B">B:  '+data.questionList[i].answerB +'<br>');
						$('#multi').append('<input type="checkbox" name="question'+ i +'" value="C">C:  '+data.questionList[i].answerC +'<br>');
						$('#multi').append('<input type="checkbox" name="question'+ i +'" value="D">D:  '+data.questionList[i].answerD +'<br>');
						$('#multi').append('<input type="hidden" name="questionId'+ i +'" value="'+data.questionList[i].id+'">');
						
					}
					for (var i=data.singleOptionNumber+data.multiOptionNumber;i < data.singleOptionNumber+data.multiOptionNumber+data.judgeNumber;i++){
						$('#judge').append('<li><strong>'+ data.questionList[i].question +'</strong><br></li>');
						$('#judge').append('<input type="radio" name="question'+ i +'" value="A">  '+data.questionList[i].answerA +'<br>');
						$('#judge').append('<input type="radio" name="question'+ i +'" value="B">  '+data.questionList[i].answerB +'<br>');
						$('#judge').append('<input type="hidden" name="questionId'+ i +'" value="'+data.questionList[i].id+'">');
					}
				}
				$('#examDialog').dialog('open');
			},'json');
	},
	submitPaper: function(){
		$.post(window.ctx + '/exam/PaperServlet?command=getPoints',$('#examForm').serialize(),function(data){
			if(data){
				 $.messager.alert('考试结果','您的考试分数为：'+data);
				 $('#examDialog').dialog('close');
				 main.init();
			}
		},'json');
	}
	}
	
};
//个人信息修改验证信息,修改密码,注销
$(function() {
	user.init();
});
$.extend($.fn.validatebox.defaults.rules, {
    equals: {
		validator: function(value,param){
			return value == $(param[0]).val();
		},
		message: '请重新输入！！'
    }
});
$.extend($.fn.validatebox.defaults.rules, {
    equals: {//验证密码两次是否相同
		validator: function(value,param){
			return value == $(param[0]).val();
		},
		message: '两次密码必须一致.'
    },
    phone: { //验证手机号   
         validator: function(value, param){ 
          return /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(177))+\d{8})$/.test(value);
         },    
         message: '请输入正确的手机号码。'   
     },
});
var user = {		
		init:function(){
			user.pwdForm = $('#pwdForm');
			user.infoForm = $('#infoForm');
		},
	operate:{
		logout: function(){
				location=window.ctx + '/test/TestServlet?command=logout';
		},
		showeditpwd:function(){
				$('#pwddlg').dialog('open');
		},
		personalInfo:function(){
			$('#infodlg').dialog('open');
		},
		checkpwd:function(obj){
			var pwd = '${sysUser.password}';
			if(pwd!=obj.value){
				$("#updatepwd").attr("disabled",true);
				$.messager.show({
					title:'提示',
					msg:'请输入正确的密码',
					timeout: 3000,
					showType:'show'
				});
			}
			else{
				$("#updatepwd").attr("disabled",false);
			}
		},
		editpwd:function(){
			user.pwdForm.form('submit', {
				url : window.ctx + '/test/TestServlet?command=updatePwd',
				 onSubmit: function(){
				 var isValid = $(this).form('validate');
				 if (!isValid){
					 $.messager.alert('警告', "填写错误！请重新输入。。", 'error');
				 }
				 return isValid;
				 },
				 success: function(data){
				 if (data=='2') {
					 $.messager.alert('警告', "填写错误！请重新输入。。", 'error');
				 }
				 if (data=='1') {
					 $('#pwddlg').dialog('close');
					 $.messager.show({
							title:'提示',
							msg:'修改成功',
							timeout: 3000,
							showType:'show'
						});
				 }
				 }
			});
		},
		editInfo:function(){
			user.infoForm.form('submit', {
				url : window.ctx + '/test/TestServlet?command=updateUser',
				 onSubmit: function(){
				 var isValid = $(this).form('validate');
				 if (!isValid){
					 $.messager.alert('警告', "填写错误！请重新输入。。", 'error');
				 }
				 return isValid;
				 },
				 success: function(data){
				 if (data) {
					 $('#infodlg').dialog('close');
					 $.messager.show({
							title:'提示',
							msg:data,
							timeout: 3000,
							showType:'show'
						});
				 }
				 }
			});
		},
}
}

$(function() {
	main.init();
});